﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;


namespace Server
{
	public class Clienthandler
	{
		private Socket client;
		private StreamReader reader;
		private StreamWriter writer;
		private AuktionsService auktionsService;

		public Clienthandler(Socket client, AuktionsService auktionsService)
		{
			this.client = client;
			NetworkStream stream = new NetworkStream(this.client);
			reader = new StreamReader(stream);
			writer = new StreamWriter(stream);
			this.auktionsService = auktionsService;

			IEnumerator<Auction> auctions = auktionsService.GetAuctions();
			auctions.Reset();

			while (auctions.MoveNext())
			{
				Auction auction = (Auction)auctions.Current;
				double hieghestBid = (auction.HeighestBid != null) ? auction.HeighestBid.Bid1 : 0;
				SendMessage("NewAuction;" + auction.Id + ";" + auction.Name + ";" + auction.MinimumPrice + ";" + hieghestBid);
			}
		}

		/// <summary>
		/// Starts the listener for the client.
		/// Best to be used in a new thread.
		/// </summary>
		public void Run()
		{
			try
			{
				while (DoSomething(reader.ReadLine()));
			}
			catch (IOException)
			{

			}
		}

		/// <summary>
		/// Sends message to client.
		/// </summary>
		/// <param name="message"></param>
		public void SendMessage(string message)
		{
			try
			{
				writer.WriteLine(message);
				writer.Flush();
			}
			catch (Exception)
			{
				return;
			}
		}

		/// <summary>
		/// Method for reading strings from the clients and doing the command they send.
		/// </summary>
		/// <param name="command"></param>
		/// <returns></returns>
		public bool DoSomething(string command)
		{
			if (command == "STOP")
				return false;

			//
			string[] commandpieces = command.Split(';');

			switch (commandpieces[0].ToLower())
			{
				case "bid":
					placeBidReturn value = auktionsService.PlaceBid(int.Parse(commandpieces[1]), double.Parse(commandpieces[2]), this);
					switch (value)
					{
						case placeBidReturn.BidOk:
							SendMessage("BidAccepted;" + commandpieces[1]);
							break;
						case placeBidReturn.BidTooLow:
							SendMessage("BidTooLow;" + commandpieces[1]);
							break;
						case placeBidReturn.AuctionClosed:
						case placeBidReturn.AuctionNotExist:
						default:
							SendMessage("AuctionNotExist;" + commandpieces[1]);
							break;
					}
					break;
				case "closing":
					auktionsService.ClientInformation("Logoff;" + client.RemoteEndPoint.ToString());
					SendMessage("OK");
					break;
				default:
					break;
			}

			return true;
		}

		public string ClientIP
		{
			get { return client.RemoteEndPoint.ToString(); }
		}
	}
}
